package com.py.credit.controller;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.entity.BatchLog;
import com.py.credit.entity.Column;
import com.py.credit.entity.Table;
import com.py.credit.service.BatchLogService;
import com.py.credit.service.ColumnService;
import com.py.credit.service.DataRelateService;
import com.py.credit.service.TableService;
import com.py.framework.core.annotation.IgnoreAuthority;

@RestController
@RequestMapping("/associationPerform")
public class AssociationPerformV2 {

	private static final Logger LOG = Logger.getLogger(AssociationPerformV2.class);

	@Autowired
	private BatchLogService batchLogService;

	@Autowired
	private DataRelateService dataRelateService;

	@Autowired
	private ColumnService columnService;

	@Autowired
	private TableService tableService;

	@IgnoreAuthority
	@RequestMapping("/associationV2.do")
	public RestServiceResult<String> Associate() throws InterruptedException {

		// 有在处理的就先调过等下次轮询
		if (batchLogService.isProcessing("P")) {

			return new RestServiceResult<String>("有批次正在处理中...");

		}

		// 未做关联的所有批次
		List<BatchLog> unAssociatedBatchLogs = batchLogService.getUnAssociatedBatch();

		if (!CollectionUtils.isEmpty(unAssociatedBatchLogs)) {
			// 取其中一个进行关联操作
			BatchLog batchLog = unAssociatedBatchLogs.get(0);
			// 更新关联状态为正在关联中
			batchLogService.updateBatchLogAssociationStatus(batchLog.getId(), "P");
			int tableId = batchLog.getTarget();
			// 实体表信息
			Table table = tableService.getTableById(tableId);
			String tableName = "t_" + table.getResourceId();
			String batchId = batchLog.getId();
			int deptId = batchLog.getDeptId();
			// 主体列表编码
			int datasourceId = batchLog.getDatasourceId();
			// 获取自动关联指标
			List<String> associationMetricCodes = dataRelateService.getAssociationMetricCodesByDbId(datasourceId);
			// 实体表的列信息
			List<Column> tableColumns = columnService.getListByTableId(tableId);
			// 判断 表里是否包含用来关联的字段,没有跳过该表的关联操作
			boolean exist = dataRelateService.existAssociationMetricCodes(tableColumns, associationMetricCodes);

			if (exist) {

				// 查看unique表里有无数据,无数据插入一条假数据(unique无数据时exist
				// 的sql语句返回为空需要加一条假数据,等数据入unique后删除)
				dataRelateService.addDummyZooUniqueIfNoData(datasourceId);
				// 调用存储过程
				Integer batchRelatePerform = dataRelateService.batchRelatePerform(String.valueOf(batchId), tableName,
						String.valueOf(datasourceId), String.valueOf(tableId), String.valueOf(deptId));
				// 存储过程返回0成功 1失败
				if (batchRelatePerform != null && batchRelatePerform == 0) {

					LOG.info("================关联成功,批次:【" + batchId + "】===============");
					// 更新批次日志关联状态为成功
					batchLogService.updateBatchLogAssociationStatus(batchId, "S");
					// 参数该批次待关联数量(记录状态为T)
					int waitCount = dataRelateService.getWaitCountByBatchId(tableName, batchId);
					// 更新待关联数量
					batchLogService.updateBatchLogWaitCount(batchId, waitCount);

				} else {
					// 更新批次日志关联状态为失败
					batchLogService.updateBatchLogAssociationStatus(batchId, "F");

					LOG.error("关联失败 ,数据表 【" + tableName + "】,批次:【" + batchId + "】,数据库:【" + datasourceId + "】");
				}
				// 删除假数据
				dataRelateService.deleteDummyZooUnique(datasourceId);

			} else {
				// 实体表中不包含关联的必要字段(A000001,B000002,C000001),更新批次日志关联状态为失败
				batchLogService.updateBatchLogAssociationStatus(batchId, "F");

				LOG.error("数据表 【" + tableName + "】不包含关联字段: " + associationMetricCodes.get(0) + ",跳过该表的关联,批次:【" + batchId
						+ "】");

				return new RestServiceResult<String>("数据表 【" + tableName + "】不包含关联字段: " + associationMetricCodes.get(0)
						+ ",跳过该表的关联,批次:【" + batchId + "】");
			}

			return new RestServiceResult<String>(batchId);

		}
		return new RestServiceResult<String>("无待关联批次...");

	}

}
